package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"user-perm-mgr/cache"
	"user-perm-mgr/modles"
	"user-perm-mgr/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	user := modles.User{
		Username: username,
		Password: password,
	}
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	err := modles.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误三次，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func UList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []modles.User

	redis_key := "list_" + strconv.Itoa(page)
	redisJoin, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisJoin == "" {
		modles.DB.Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisJoin), &data)
	}
	var total int64
	modles.DB.Model(&modles.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	uid := c.Query("uid")
	var data modles.User

	redis_key := "detail_" + uid
	redisJoin, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisJoin == "" {
		modles.DB.Where("id=?", uid).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisJoin), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
